const BaseHandler     = require('../base-handler');
const SystemServices  = require('../../../constants').SystemServices;
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;

class SettingsProfileHandler extends BaseHandler {
    get pattern() {
        return "/settings/profile";
    }

    doGET(request, response) {
        response.redirect("/setprofile");
    }

    doPOST(request, response) {
        if (!request.session.user.authenticated) {
            response.json({
                success: false,
                error: '非法操作!'
            });
        } else {
            var me = this;
            request.body.userId = request.session.user.id;
            request.body.newpwd = request.body.newPassword;
            delete request.body.newPassword;
            request.body.oldpwd = request.body.oldPassword;
            delete request.body.oldPassword;
            
            this.Controller.updateUserProfile(request.body, function (result) {
                if(result.success){
                    request.body.userName && (request.session.user.name = request.body.userName);
                    request.body.nickName && (request.session.user.nickName = request.body.nickName);
                    request.body.email && (request.session.user.email = request.body.email);

                    response.json({
                        success: true,
                        result: result
                    })
                } else {
                    response.json({
                        success: false,
                        error: result.error
                    })
                }
            });
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
        this.registerVerb(HTTP_VERBS.POST, this.doPOST);
    }
}

module.exports = SettingsProfileHandler;